const fs = require('fs');
const path = require('path');
const { spawn } = require('child_process');
const fss = require('fs');
const config = JSON.parse(fs.readFileSync(path.join(__dirname, "../..", "config.json"), "utf8"));

// 移动到单独的文件中
/**
 * Whisper转录器类
 */
class WhisperTranscriber {
  /**
   * 转录音频/视频文件
   * @param {string} inputPath - 输入文件路径
   * @param {Object} options - 转录选项
   * @returns {Promise<Object>} 转录结果对象
   */
  static transcribe(inputPath, options = {}) {
    return new Promise((resolve, reject) => {
      // 确保输入文件存在
      if (!fss.existsSync(inputPath)) {
        reject(new Error(`Input file not found: ${inputPath}`));
        return;
      }

      // 设置默认选项
      const opts = {
        model: options.model || 'base',
        language: options.language || 'en',
        verbose: options.verbose || 'True',
        output_format: options.output_format || 'all', // 生成所有格式
        ...options
      };

      // 创建临时目录用于存储模型和输出
      const tempDir = path.join(__dirname, "../../",config.temp);
      const modelDir = path.join(tempDir, "whisper_models");
      
      if (!fss.existsSync(modelDir)) {
        fss.mkdirSync(modelDir, { recursive: true });
      }

      // 构建命令参数
      const args = [
        '-m', 'whisper',
        inputPath,
        '--model', opts.model,
        '--model_dir', modelDir,
        '--language', opts.language,
        '--verbose', opts.verbose,
        '--output_dir', tempDir,
        '--output_format', opts.output_format
      ];

      console.log('Running Whisper with args:', args);

      // 执行Whisper命令
      const child = spawn('python', args);

      let stderr = '';

      // 收集输出
      child.stderr.on('data', (data) => {
        stderr += data.toString();
      });

      // 处理进程结束
      child.on('close', (code) => {
        if (code === 0) {
          // 读取生成的转录文件
          console.log(tempDir);
          console.log(inputPath);
          
          const srtFilePath = path.join(tempDir, path.basename(inputPath,".mp4") + '.srt');
          console.log(srtFilePath);
          
          const result = {};
          
          if (fss.existsSync(srtFilePath)) {
            result.srt = fss.readFileSync(srtFilePath, 'utf8');
          }

          resolve(result);
        } else {
          reject(new Error(`Whisper process failed with code ${code}: ${stderr}`));
        }
      });

      // 处理启动错误
      child.on('error', (error) => {
        reject(new Error(`Failed to start Whisper process: ${error.message}`));
      });
    });
  }

  /**
   * 将SRT格式转换为ASS格式
   * @param {string} srtContent - SRT内容
   * @param {string} assHeader - ASS头部
   * @returns {string} ASS内容
   */
  static srtToAss(srtContent, assHeader) {
    if (!srtContent) return assHeader || '';
    
    // 解析SRT内容
    const lines = srtContent.split('\n');
    let assEvents = '';
    let i = 0;
    
    while (i < lines.length) {
      const line = lines[i].trim();
      
      // 检查是否是时间戳行
      if (line.includes('-->')) {
        const timeMatch = line.match(/(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/);
        if (timeMatch) {
          // 转换时间格式 (SRT使用逗号, ASS使用点)
          const startTime = timeMatch[1].replace(',', '.');
          const endTime = timeMatch[2].replace(',', '.');
          
          // 获取下一行作为文本
          i++;
          let text = '';
          while (i < lines.length && lines[i].trim() !== '' && !/^\d+$/.test(lines[i].trim()) && !lines[i].includes('-->')) {
            if (text) text += ' ';
            text += lines[i].trim();
            i++;
          }
          
          // 添加到ASS事件中
          if (text) {
            assEvents += `Dialogue: 0,${startTime},${endTime},Current,,0,0,0,,${text}\n`;
          }
        }
      }
      i++;
    }
    
    // 组合完整的ASS内容
    return (assHeader || '') + assEvents;
  }

  /**
   * 获取SRT文件路径
   * @param {string} inputPath - 输入文件路径
   * @returns {string} SRT文件路径
   */
  static getSrtFilePath(inputPath) {
    const tempDir = path.join(__dirname, "../../temp");
    return path.join(tempDir, path.basename(inputPath) + '.srt');
  }
}

module.exports = { WhisperTranscriber };